import { useUserStore } from '@/store/user.js'

/**
 * 请求拦截器，自动添加token
 * @param {Object} config
 * @returns {Object}
 */
export const requestInterceptor = (config) => {
  const header = {
    'Content-Type': 'application/json',
    ...config.header
  }
  // 自动添加token
  const userStore = useUserStore()
  const accessToken = userStore.accessToken
  if (accessToken) {
    header['token'] = accessToken
  }
  return {
    ...config,
    header
  }
}

/**
 * 响应拦截器，统一处理响应数据
 * @param {Object} response
 * @returns {Object}
 * @throws {Object} 抛出错误响应对象
 */
export const responseInterceptor = (response) => {
  if (response.statusCode === 200) {
    if (response.data.code !== '0') {
      // token失效处理 - 直接抛出错误，由上层处理
      if (response.data.code === '8001') {
        throw response;
      }
      // 其他业务错误
      uni.showToast({
        title: response.data.message || '请求失败',
        icon: 'none'
      });
      throw response;
    }
    return response.data;
  } else {
    uni.showToast({
      title: response.data?.message || '请求失败',
      icon: 'none'
    });
    throw response;
  }
}

/**
 * 错误拦截器，统一处理错误
 * @param {Object} error
 * @returns {Promise}
 */
export const errorInterceptor = (error) => {
  uni.showToast({
    title: '网络错误，请检查网络连接',
    icon: 'none'
  })
  return Promise.reject(error)
}